package com.glodon.utils.service;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.glodon.spring.service.BulletinService;

public class MessageAcceptService implements MessageListener {

    private static final Logger log = LoggerFactory.getLogger(MessageAcceptService.class);

    @Autowired
    private BulletinService bulletinService;
    /**
     * 消费数据
     * @param message
     * @param consumeContext
     * @return
     */
    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {

        //如果想测试消息重投的功能,可以将Action.CommitMessage 替换成Action.ReconsumeLater
        try {
            if("test".equals(message.getTag())){
//                bulletinService.accessMsg(message.getBody());

                bulletinService.accessMsg(new String(message.getBody(), "GBK"));
                log.info(new Date() + " 交卷成功, Topic is:" + message.getTopic() + ", MsgId is:" + message.getMsgID());
            }
            return Action.CommitMessage;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("消息队列处理错误，消息id : {} ,tag :{}, msg：{} ,cause :{}" ,message.getMsgID() ,message.getTag() , e.getMessage() , e.getCause());
            return Action.ReconsumeLater;
        }
    }
}